﻿#include "remindonce.h"
#include "ui_remindonce.h"

RemindOnce::RemindOnce(QWidget *parent,const QSqlDatabase &db) :
    BaseEditorDialog(parent),_db(db),
    ui(new Ui::RemindOnce)
{
    ui->setupUi(this);

    table=TD_ONCE;

    model=new QSqlTableModel(this,_db);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);

    updateView();
    createMenu();
}

RemindOnce::~RemindOnce()
{
    delete ui;
}

void RemindOnce::updateView()
{
    model->setTable(table);
    model->setFilter(QString("host='%1'").arg(QHostInfo::localHostName()));
    model->select();

    ui->tableView->hideColumn(0);   //uid
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("时间"));    //target
    ui->tableView->setColumnWidth(1,200);
    ui->tableView->hideColumn(2);   //detail
    ui->tableView->hideColumn(3);   //host
}

void RemindOnce::createMenu()
{
    menu=new QMenu(this);
    menu->addAction(QStringLiteral("添加..."),this,&RemindOnce::addItem);
    menu->addAction(QStringLiteral("查找..."),this,&RemindOnce::search);
    menu->addSeparator();
    menu->addAction(QStringLiteral("更新"),this,&RemindOnce::updateView);

    menu->addSeparator();
    menu->addAction(QStringLiteral("保存"),this,&RemindOnce::save);
    menu->addAction(QStringLiteral("撤销"),this,&RemindOnce::revert);
    menu->addSeparator();
    menu->addAction(QStringLiteral("【删除】"),this,&RemindOnce::removeItem);
}

void RemindOnce::search()
{
    showSearchBox("target");
}

void RemindOnce::addItem()
{
    AddOnce item(this,_db);
    if(item.exec() == QDialog::Accepted)
        updateView();
}

void RemindOnce::removeItem()
{
    if(ui->tableView->currentIndex().isValid())
    {
        int row=ui->tableView->currentIndex().row();
        model->removeRow(row);
    }
}

void RemindOnce::on_tableView_clicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QSqlRecord record=model->record(index.row());
        uid=record.value("uid").toString();
        QString detail=record.value("detail").toString();
        ui->detail->setPlainText(detail);
    }
}

void RemindOnce::on_btn_clean_clicked()
{
    if(!ui->detail->toPlainText().isEmpty())
        ui->detail->clear();
}

void RemindOnce::on_btn_save_clicked()
{
    QString detail=ui->detail->toPlainText();
    QSqlQuery query(_db);
    QString sql;

    if(!detail.isEmpty())
        sql=QString("update %1 set detail='%2' where uid='%3'").arg(table)
                .arg(detail)
                .arg(uid);
    else
        sql=QString("delete from %1 where uid='%2'").arg(table)
                .arg(uid);

    if(!query.exec(sql))
        QMessageBox::critical(this,QStringLiteral("异常情况"),QStringLiteral("异常情况！保存失败！"));
    else
        updateView();
}

void RemindOnce::on_btn_start_clicked()
{
    emit timerStart();
    close();
}
